package com.zyg.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.dao.ClassMapper;
import com.zyg.pojo.Class;
import com.zyg.pojo.Grade;
import com.zyg.service.ClassService;
import com.zyg.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("classService")
public class ClassServiceImpl extends ServiceImpl<ClassMapper, Class> implements ClassService {

    @Autowired
    private GradeService gradeService;

    @Override
    public IPage<Class> listWithGrade(IPage<Class> page, QueryWrapper<Class> queryWrapper) {
        // ��ѯ�༶����
        IPage<Class> classPage = baseMapper.selectPage(page, queryWrapper);

        // ��ȡ���а༶���꼶ID
        List<Long> gradeIds = classPage.getRecords().stream()
                .map(Class::getGradeId)
                .distinct()
                .collect(Collectors.toList());

        // �����꼶ID��ѯ�꼶��Ϣ
        Map<Long, Grade> gradeMap = gradeService.listByIds(gradeIds).stream()
                .collect(Collectors.toMap(Grade::getGradeId, grade -> grade));

        // ���ð༶������꼶��Ϣ
        classPage.getRecords().forEach(clazz -> {
            if (clazz.getGradeId() != null && gradeMap.containsKey(clazz.getGradeId())) {
                clazz.setGrade(gradeMap.get(clazz.getGradeId()));
            }
        });

        return classPage;
    }

}
